package uk.ac.cam.djjb2.mygame;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientNetManager extends NetManager {
	private Socket socket;
	private DataInputStream inputStream;
	private DataOutputStream outputStream;
	private Thread clientThread;
	
	public ClientNetManager(InetAddress address, int port) throws IOException {
		socket = new Socket(address, port);
		inputStream = new DataInputStream(socket.getInputStream());
		outputStream = new DataOutputStream(socket.getOutputStream());

		clientThread = new Thread(new Runnable() {
			public void run(){
				clientThread();
			}
		});
		clientThread.start();
	}
	
	private void clientThread() {
		try {
			while (!socket.isClosed()) {
				MessageInputStream message = new MessageInputStream(inputStream);
				postMessage(0, message);
			}
		} catch (IOException e) {
		}
	}

	public MessageOutputStream createMessageStream() throws IOException {
		return new MessageOutputStream(outputStream);
	}
}
